<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:category:remove']"
        >删除</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="自增主键" align="center" prop="id" />
      <el-table-column label="轮播图集合,json格式: [{"img":"","enable":"1"}],img:图片路经,enable:0-未启用;1-启用" align="center" prop="urls" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:category:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:category:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改首页轮播图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="260px">
        <el-row>
          <el-col :span="2" ></el-col>
          <el-col :span="20" >首页轮播图上传</el-col>
        </el-row>
        <el-row style="margin-top: 30px;">
          <el-col :span="2" ></el-col>
          <el-col :span="20" >
            <el-upload
              action="/dev-api/system/category/upload"
              ref="upload"
              :headers="headers"
              multiple
              :limit="6"
              list-type="picture-card"
              :file-list="fileList"
              :before-upload="beforeAvatarUpload"
              :on-exceed="handleExceed"
              :on-error="onError"
              :on-success="onSuccess"
              :auto-upload="true">
                <i slot="default" class="el-icon-plus" ></i>
                <div slot="file" slot-scope="{file}" v-if="file.url!=null">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <!-- <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleDownload(file)"
                    >
                      <i class="el-icon-download"></i>
                    </span> -->
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
            </el-upload>
          </el-col>
        </el-row>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, exportCategory, uploadImg } from "@/api/system/category";
import { getToken } from '@/utils/auth'
export default {
  name: "Category",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 首页轮播图表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      headers:{'Authorization': null},
      fileList:[],
      fileList2:[],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    };
  },
  created() {
    this.getList();
    const token = 'Bearer ' + getToken()
    this.headers.Authorization = token
  },
  methods: {
    /** 查询首页轮播图列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        urls: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = []
      this.fileList2 = []
      this.reset();
      this.open = true;
      this.title = "添加首页轮播图";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList = []
      this.fileList2 = []
      this.reset();
      const id = row.id || this.ids
      getCategory(id).then(response => {
        this.form = response.data
        const arry = this.form.urls!=null?this.form.urls.split(","):[]
        for (let i = 0; i < arry.length; i++) {
          let a = arry[i].split("/")
          let name = a[a.length-1]
          this.fileList.push({name:name, url: 'http://localhost:1000'+arry[i]})
          this.fileList2.push({name:name, url: arry[i]})
        }
        console.log("this.fileList", this.fileList2)
        this.open = true;
        this.title = "修改首页轮播图";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.urls = ""
          for (var i = 0; i < this.fileList2.length; i++) {
            this.form.urls += this.fileList2[i].url + ","
          }
          this.form.urls = this.form.urls.substr(0, this.form.urls.length - 1)
          if (this.form.id != null) {
            updateCategory(this.form).then(response => {
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$message({
                message: '新增成功',
                type: 'success'
              });
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除首页轮播图编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCategory(ids);
        }).then(() => {
          this.getList();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有首页轮播图数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCategory(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      console.log("handlePictureCardPreview file", file);
    },
    handleDownload(file) {
      console.log(file);
    },
    handleRemove(file) {
      this.$confirm(`确定移除 ${ file.name }？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (var i = 0; i < this.fileList.length; i++) {
          if(this.fileList[i].name == file.name){
            this.fileList.splice(i, 1)
            this.fileList2.splice(i, 1)
            break
          }
        }
      }).catch(() => {});

    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`您已超过了最大上传图片个数`);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      return isJPG;
    },
    onError(err, file, fileList){
      console.log("onError err", err)
    },
    onSuccess(response, file, fileList){
      this.fileList = fileList
      this.fileList2.push({name:file.name,url:response.msg})
      console.log("onSuccess file", file)
      console.log("onSuccess fileList", fileList)
    },
  }
};
</script>
